import axios from 'axios';
import store from '@/store';
import router from "@/router";
import {ACCESS_TOKEN} from "@/store/mutations-type";
import {getCookie, setCookieExpire, removeCookie} from "@/api/provider/cookieProvider";
import {message, notification, Modal} from "ant-design-vue";
import {setCookie} from "@/utils/auth";
//设置全局API_BASE_URL
let apiBaseUrl = '/';
// 创建axios实例
const service = axios.create({
    baseURL: apiBaseUrl, // api base_url
    timeout: 9000 // 请求超时时间
});

// request拦截器
service.interceptors.request.use(request => {
    // 拦截所有请求，并将其请求头位置加入token信息 - 这里拿去的是vuex中的token- mian.js中将token存入了
    request.headers[ACCESS_TOKEN] = getCookie(ACCESS_TOKEN);
    return request;
}, error => {
    // 如果发生请求异常
    console.log(error);// for debug
    return Promise.reject(error);
});

// response拦截器 - 注意经过本次拦截 所有和这个有关的请求返回对象只是统一的返回格式 result{ code message record }
service.interceptors.response.use(
    (response) => {
        switch (response.data.code) {
            case 201:
                goToLogin("您尚未登录，点击确认即可跳转至登录页面", "info");
                break;
            case 202:
                // 发起刷新token功能
                handleRefreshToken();
                break;
            case 203:
                goToLogin(response.data.code.message, "warn");
                break;
            case 204:
                goToLogin(response.data.code.message, "error");
                break;
            default:
                break;
        }
        return response.data;
    },
    (error) => {
        return Promise.reject(error);
    });

function handleRefreshToken() {
    service({
        url: "/commonApi/refreshToken",
        method: "put",
    }).then(res => {
        if (res.success) {
            setCookie(ACCESS_TOKEN, res.result.token);
        } else {
            message.error(res.message);
        }
    })
}

function handleError(content, okProcessor, key, mode) {
    notification[mode]({
        message: '信息提示',
        description: content,
        duration: null,
        btn: createElement => {
            return createElement(
                'a-button',
                {
                    props: {
                        type: 'primary',
                    },
                    on: {
                        click: okProcessor,
                    },
                },
                '确认',
            );
        },
        key,
        onClose: close,
        top: "100px"
    })
}

function goToLogin(content, mode) {
    const key = `open${Date.now()}`;
    const handleFunction = () => { // 移除cookie中的无效token信息
        removeCookie(ACCESS_TOKEN);
        store.commit("SET_TOKEN", null);
        try {
            let path = router.history.current.fullPath;
            if (path.indexOf("/login") === -1) {
                router.replace({path: '/login'});
            }
        } catch (e) {
            window.location.reload()
        }
        notification.close(key)
    }
    handleError(content, handleFunction, key, mode);
}

export default service;
